package com.oceansoft.mobile.filter;

import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import net.sf.ehcache.constructs.blocking.LockTimeoutException;
import net.sf.ehcache.constructs.web.AlreadyCommittedException;
import net.sf.ehcache.constructs.web.AlreadyGzippedException;
import net.sf.ehcache.constructs.web.filter.FilterNonReentrantException;
import net.sf.ehcache.constructs.web.filter.SimplePageCachingFilter;

public class PageEhCacheFilter extends SimplePageCachingFilter{
	private final static Logger log = Logger.getLogger(PageEhCacheFilter.class);
	
    private final static String FILTER_URL_PATTERNS = "patterns";
    private static String[] cacheURLs;
    
    private void init() {
        String patterns = filterConfig.getInitParameter(FILTER_URL_PATTERNS);
        cacheURLs = StringUtils.split(patterns, ",");
    }
    
    @Override
    protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws AlreadyGzippedException, AlreadyCommittedException, FilterNonReentrantException, LockTimeoutException, Exception {
    	if(null == cacheURLs)
    		this.init();
    	
    	//清除URL中的sessionid
    	if (request.isRequestedSessionIdFromURL()) {  
            HttpSession session = request.getSession();  
           if (session != null) session.invalidate();  
        }
    	
    	//配置中是否包含需要缓存的路径
    	boolean isContain = false;
    	String url = request.getRequestURI();
    	//log.info("============当前访问路径：" + url);
//    	System.out.println("当前访问路径：" + url);
    	if(StringUtils.isNotBlank(url)){
    		for (String cacheURL : cacheURLs) {
                if (url.indexOf(cacheURL.trim())!=-1) {
                	isContain = true;
                    break;
                }
            }
    	}
    	
        // 如果包含我们要缓存的url 就缓存该页面，否则执行正常的页面转向
        if (isContain) {
            String query = request.getQueryString();
            if (query != null) {
                query = "?" + query;
            }
            log.info("当前请求被缓存：" + url + (StringUtils.isNotEmpty(query)?query:""));
            super.doFilter(request, response, chain);
        } else {
            chain.doFilter(request, response);
        }
    }
}
